package com.zycfc.zsf.boot.mybatis.typehandler;

import org.apache.ibatis.type.*;
import org.springframework.util.*;
import java.util.*;
import java.sql.*;

public class IntegerSetTypeHandler extends BaseTypeHandler<Set<Integer>>
{
    private final String delimiter;
    
    public IntegerSetTypeHandler() {
        this.delimiter = ",";
    }
    
    public IntegerSetTypeHandler(final String delimiter) {
        this.delimiter = delimiter;
    }
    
    public void setNonNullParameter(final PreparedStatement ps, final int i, final Set<Integer> parameter, final JdbcType jdbcType) throws SQLException {
        ps.setString(i, StringUtils.collectionToDelimitedString((Collection)parameter, this.delimiter));
    }
    
    private Set<Integer> stringToSet(final String string) {
        final String[] array = StringUtils.tokenizeToStringArray(string, this.delimiter);
        Set<Integer> res = null;
        if (null != array && array.length > 0) {
            res = new LinkedHashSet<Integer>(array.length);
            for (final String item : array) {
                Integer val = null;
                if (null != item && item.length() > 0) {
                    val = Integer.valueOf(item);
                }
                res.add(val);
            }
        }
        return res;
    }
    
    public Set<Integer> getNullableResult(final ResultSet rs, final String columnName) throws SQLException {
        final String str = rs.getString(columnName);
        if (rs.wasNull()) {
            return null;
        }
        return this.stringToSet(str);
    }
    
    public Set<Integer> getNullableResult(final ResultSet rs, final int columnIndex) throws SQLException {
        final String str = rs.getString(columnIndex);
        if (rs.wasNull()) {
            return null;
        }
        return this.stringToSet(str);
    }
    
    public Set<Integer> getNullableResult(final CallableStatement cs, final int columnIndex) throws SQLException {
        final String str = cs.getString(columnIndex);
        if (cs.wasNull()) {
            return null;
        }
        return this.stringToSet(str);
    }
}
